package com.jushu.storbox.util.identity;

import java.io.InputStream;
import java.security.MessageDigest;


public class StreamMD5FileIdentity extends AbsStreamIdentity {

	public StreamMD5FileIdentity(InputStream inputStream, IidentityCallback callback) {
		super(inputStream, callback);
	}

	@Override
	protected String doComputeIdentity() throws Exception  {
		byte[] tempBuffer = new byte[BUFFER_SIZE];
		int len = -1;
		long currentProgress = 0;
		long oldProgress = 0;
		long progress = 0;
		MessageDigest messageDigest = MessageDigest.getInstance("MD5");
		int fileSize = innerStream.available();
		while((len = innerStream.read(tempBuffer)) != -1){
			messageDigest.update(tempBuffer, 0, len);
			currentProgress = len;
			oldProgress = currentProgress * 100 / fileSize;
			if ( progress != oldProgress) {
				progress = oldProgress;
				IdentityCallback.onProgress((int) progress,
						(long) currentProgress, fileSize);
			}
		}
		innerStream.reset();
		identity = bytes2String(messageDigest.digest());
		return identity;
	}

}
